import React,{Component} from 'react';
import { Icon, Input, Button, Form, Table, Pagination, message, Modal } from 'antd';
import { Link } from 'react-router-dom';
import ReactDOM from 'react-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
const FormItem = Form.Item;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

const Token = localStorage.getItem("token");
class certificatemanagement extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			data: [],
			page:['10','20','30','40','50','60','70','80','90'],
			page_1: 1,
			limit: 10,
			visible: false,
			getCode: '',
			id: '',
			secretType: '',
			expireTime: '',
			oldMobile: '',
			serialNumber: '',
			aki: '',
			certType: '',
			dn: '',
			reason: '',
			bjcaPwd: '',
			downloadLink: '',
			secretName: '',
		}
	}
 	
 	componentWillMount(){
 		this.getData(this.state.page_1,this.state.limit);
	}


	componentWillUpdate(nextProps){
		if(nextProps.changeOrgid != this.props.changeOrgid){
			this.getData(this.state.page_1,this.state.limit,nextProps.changeOrgid);
		}
	}

	columns = [{
		title: '证书ID',
		dataIndex: 'id',
		key: 'id',
	},{
		title: '证书类型',
		dataIndex: 'secretType',
		key: 'secretType',
	},{
		title: '到期时间',
		dataIndex: 'expireTime',
		key: 'expireTime',
	},{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
	},{
		title: '操作',
		key: '操作',
		width: 260,
		render: (text) => (
			<div>
				<span className={(text['status'] == '使用中' || text['status'] == '作废') ? 'userBtn disabledClass': 'userBtn'} onClick={this.useCertificate.bind(this,text)} style={{marginRight: 10}}>使用该证书</span>
				<span className={(text['status'] == '作废') ? 'btnColor disabledClass': 'btnColor'} style={{marginRight: 10}}><a href={(text['status'] == '作废') ? 'javascript:;': '/api/block/baas/Ca/downloadFileCa?id='+text.id+'&token='+Token}>下载证书</a></span>
				<span className={(text['status'] == '使用中' || text['status'] == '作废') ? 'btnColor disabledClass': 'btnColor'} onClick={this.cancelCertificate.bind(this,text)}>作废证书</span>
			</div>
		)
	}];

	handleCancel =()=>{
		this.setState({
			visible: false
		})
	}
	//使用该证书交互
	useCertificate =(text)=>{
		const _this = this;
		const Token = localStorage.getItem("token");
		if(text['status'] == '使用中' || text['status'] == '作废'){
			return
		}else{
			axios({
				method: 'post',
				url: '/api/block/baas/Ca/userCert?serialNum='+text.serialNum,
				headers: {
				  'Content-Type': 'application/json',
				  Authorization: Token,
				}
			})
			.then(function(response){
				// console.log(response.data.message)	
				if(response.data.message == '证书已被选中!'){
					_this.getData(_this.state.page_1,_this.state.limit,_this.props.changeOrgid);
				}
			})
			.catch(function(error){
				console.log('error')
			})
		}
		
	}
	//作废该证书交互
	cancelCertificate =(text)=>{
		if((text['status'] == '使用中' || text['status'] == '作废')){
			return
		}else{
			this.setState({
				visible: true,
				id: text['id'],
				secretType: text['secretType'],
				certType: text['certType'],
				expireTime: text['expireTime'],
				serialNumber: text.serialNum,
				secretName: text.secretName,
				aki: text.aki,
				dn: text.dn,
				reason: text.reason,
				bjcaPwd: text.bjcaPwd,
			})
			const _this = this;
			const nowDate = new Date().getTime();
			let sec = localStorage.getItem("noUseclickTime");
			const currentTime = (nowDate - sec)/1000;
			let delta = Math.round(60 - currentTime);
			const timer = setInterval(function(){
				delta--;
				if(delta < 0){
					clearInterval(timer);
					_this.setState({
						getCode:  '获取验证码',
					})
					localStorage.setItem("noUseclickTime","");
				}else {
					_this.setState({
						getCode:  delta + 's 后重新获取',
					})
				}
			},1000)
			const Token = localStorage.getItem("token");
			axios({
			  method: 'get',
			  url: '/api/customer/user/getTel',
			  headers: {
			    'Content-Type': 'application/json',
			    Authorization: Token,
			  }
			})
			.then(function(response){
			  if(response.data.code == '200'){
			    _this.setState({
			        oldMobile: response.data.data,
			    })
			  }
			})
			.catch(function(error){
			  message.error('获取手机号失败') 
			})
		}	
	}

	handleSubmit = ()=>{
		const _this = this;
		const Token = localStorage.getItem("token");
		const serialNumber = this.state.serialNumber;
		const certType = this.state.certType;
		const aki = this.state.aki;
		const dn = this.state.dn;
		const reason = this.state.reason;
		const bjcaPwd = this.state.bjcaPwd;
		const phone = this.state.oldMobile;
		const secretName = this.state.secretName;
		_this.props.form.validateFields((err, values) => {
			if(!err){
				var cancelData = {
					caType: certType,
            		serialNumber: serialNumber,
            		aki: aki,
            		dn: dn,
            		reason: reason,
            		bjcaPwd: bjcaPwd,
            		alias: secretName,
            	}
				axios({
					method: 'get',
					url: '/api/customer/rest/checkMsg?mobile='+ phone +'&code='+ values.code,
	                headers: {
	                  'Content-Type': 'application/json',
	                  Authorization: Token,
                	}
                })	
                .then(function(response){
                	if(response.data.data == 'error'){
                		 message.warning('请输入正确的验证码');
                	}else if(response.data.data == 'success'){
                		//此处填写作废证书弹窗提交接口
                		// console.log(cancelData);
                		axios({
                			method: 'post',
                			url: '/api/block/baas/Ca/cancelCa',
                			data: cancelData,
			                headers: {
			                  'Content-Type': 'application/json',
			                  Authorization: Token,
		                	}
                		})
                		.then(function(response){
                			// console.log(response)
                			if(response.data.message == '证书注销失败!'){
                				message.error('证书注销失败!');
                			}else if(response.data.message == '证书注销成功!'){
                				message.success('证书注销成功!');
								// _this.getData(_this.state.page_1,_this.state.limit,_this.props.changeOrgid);
                			}
                				_this.setState({
									visible: false,
								})
                		})
                		.catch(function(error){
                			console.log(error)
                		})
                	}
                })
			}else {
				console.log('Received values of form: ', values);
			}
		})
	}

	onShowSizeChange=(current, pageSize)=> {
		console.log(current, pageSize);
		this.getData(current, pageSize);
		this.setState({
			limit: pageSize
		})
	}
	onChange=(pageNumber)=> {
	  console.log('Page: ', pageNumber);
	  this.getData(pageNumber);
	}
	
	getData= (page,limit = this.state.limit,orgid = this.props.changeOrgid)=>{
		const _this = this;
		const Token = localStorage.getItem("token");
		if(!orgid){ return}
		axios({
			method: 'get',
			url: '/api/block/baas/Ca/queryAllBaasCa',
			headers: {
				'Content-Type': 'application/json',
				Authorization: Token,
			},
			params: {
				orgId: orgid,
				page: page,
				limit: limit
			}
		})
		.then(function (response) {
			// console.log(response);
			let data = [];
			let secretType = '';
			let certStatus = '';
			response.data&&response.data.data&&response.data.data.rows&&response.data.data.rows.forEach((e,i)=>{
				if(e.secretType == 1){
					secretType = '默认证书'
				}else {
					secretType = '付费证书'
				}
				if(e.certStatus == 1){
					certStatus = '备选'
				}else if(e.certStatus == 2){
					certStatus = '使用中'
				}else{
					certStatus = '作废'
				}
				data.push({
					key: i+'',
					"id": e.secretName,
					"secretType": secretType,
					"expireTime": e.expireTime,
					"status": certStatus,
					certPath: e.certPath,
					serialNum: e.serialNum,
					aki: e.aki,
					dn: e.dn,
					reason: e.reason,
					bjcaPwd: e.bjcaPwd,
					certType: e.certType,
					secretName: e.secretName,
				})
			})
			_this.setState({
				data: data,
				totalnum: response.data.data.total,
			})
		})
		.catch(function (error) {
			message.error('请求失败，请刷新重试。')
		});
		
	}	

	handleCode =()=>{
		const _this = this;
		let sec = 60;
		const clickTime = new Date().getTime();
		localStorage.setItem("noUseclickTime",clickTime);
		const mobile = this.state.oldMobile;
		const Token = localStorage.getItem("token");
		if(this.state.getCode !== '获取验证码'){
			return false;
		}
		axios({
		  method: 'get',
		  url: '/api/customer/rest/sendMsg?mobile='+ mobile,
		  headers: {
		    'Content-Type': 'application/json',
		    Authorization: Token,
		  }
		})
		.then(function(response){
		  if(response.data.code == '201'){
		    message.warning('请输入正确的手机号');
		  }else if(response.data.code == '202'){
		    message.warning('获取手机验证码失败');
		  }else if(response.data.code == '200') {
		    const timer = setInterval(function(){
		      sec--;
		      if(sec < 0){
		        clearInterval(timer);
		        _this.setState({
		          getCode:  '获取验证码',
		        })
		      }else {
		        _this.setState({
		          getCode:  sec + 's 后重新获取',
		        })
		      }
		    },1000)
		    localStorage.setItem("noUseclickTime","");
		  }
		})
	}

	search = (err)=>{
    	//此处填写搜索交互
    	if(!err){

    	}else {
    		message.error('搜索有误');
    	}
    }

	// maxLength =(e)=>{
	//   if(!Number(e.target.value)){
	//     message.warning('请输入数字');
	//   }
	// }

	render() {
		const { visible, id, secretType, expireTime } = this.state;
		const { getFieldDecorator } = this.props.form;
		const disabled = this.state.getCode !== '获取验证码' ? "disabled" : "";
		return (
				<div>
					<div>
						<div className="index-buttons">
							<Link to="/certificateManagement/createKey"><Button type="primary">创建一个证书</Button></Link>
						</div>
						{/*<div className="inviteUserBox">
							<Input placeholder="请输入证书ID" className="input" />
							<Button type="primary" className="search" onClick={this.search}><img src={require('./img/search_icon.png')} /></Button>
						</div>*/}
					</div>	
					<Table 
					columns={this.columns} 
					dataSource={this.state.data} 
					bordered
					pagination={false} />
					<div className="page_foot">
						<span className="data_num">共{this.state.totalnum}条</span>
						<Pagination 
							pageSizeOptions={this.state.page} 
							className="page" 
							showSizeChanger 
							showQuickJumper
							onShowSizeChange={this.onShowSizeChange} 
							defaultCurrent={1} 
							total={this.state.totalnum} 
							onChange={this.onChange} />
					</div>
					<Modal
					  visible={visible}
					  title="提示"
					  iconType="warning"
					  onCancel={this.handleCancel}
					  footer={[
					    <Button key="back" onClick={this.handleCancel}>取消</Button>,
					    <Button key="submit" type="primary" onClick={this.handleSubmit}>确定</Button>
					  ]}
					>
					  <div className="cancelCertificate">
					  	<h3 className="cancelTitle">确定要作废此证书吗？</h3>
					  	<Form>
					  		<FormItem
					  		    label="证书ID"
					  		    labelCol={{ span: 7 }}
					  		    wrapperCol={{ span: 16 }}
					  		>
					  			<p className="infoItem">{id}</p>
					  		</FormItem>
					  		<FormItem
					  		    label="证书类型"
					  		    labelCol={{ span: 7 }}
					  		    wrapperCol={{ span: 16 }}
					  		>
					  			<p className="infoItem">{secretType}</p>
					  		</FormItem>
					  		<FormItem
					  		    label="到期时间"
					  		    labelCol={{ span: 7 }}
					  		    wrapperCol={{ span: 16 }}
					  		>
					  			<p className="infoItem">{expireTime}</p>
					  		</FormItem>
		  					<FormItem className="namePhone"
		  					    label="预留手机号"
		  					    labelCol={{ span: 7 }}
		  					    wrapperCol={{ span: 14 }}
		  					>	
		  						{getFieldDecorator('phone',{
		  							rules: [{required: false, message: '请输入手机号码'}]
		  						})(
		  							<div>
		  		                        <Input className="phoneText" disabled value={this.state.oldMobile} maxLength={11} />
		  		                        <Button
		  						            className="yzmBtn"
		  						            type= "primary"
		  						            size="small"
		  						            // disabled
		  						            disabled={disabled}
		  						            onClick = {this.handleCode}
		  						          >
		  						          {this.state.getCode}
		  					        	</Button>
		  		                    </div> 
		  						)}
		  					</FormItem>
		  					<FormItem
		  					    label="短信验证码"
		  					    labelCol={{ span: 7 }}
		  					    wrapperCol={{ span: 14 }}
		  					>	
		  						{getFieldDecorator('code',{
		  							rules: [{required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/}]
		  						})(
		  							<Input type="text" placeholder="请输入短信验证码，仅限数字" maxLength={8} />
		  						)}
		  					</FormItem>
		  					<p className="cancelTitle cancelClass">证书作废后将无法正常使用，且不可恢复，您确认要作废此证书吗？</p>
					  	</Form>
					  </div>
					</Modal>
					<div id='downloadDiv' style={{display:'none'}}></div>
				</div>
					
		);
	}
}
const certificateManagement = Form.create()(certificatemanagement);
export default connect((state) => {
	return { ...state };
})(certificateManagement);
